import React, { useLayoutEffect, useMemo, useRef, useState } from "react";
import { ResourceList } from "../../Component/ResourceList";
import { FormattedMessage, useIntl } from "react-intl";
import { LibAppView } from "@/lib";
import { Button, App, Tag } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useDelete } from "../../hooks/useDelete";
import lodash from "lodash";
import { AdminRight } from "@/pages/Admin/data/AdminPageAuth";
import ResourceStatus from "../../Component/ResourceStatus";
import { useActivityApplyReview } from "../../Layout/Review/useActivityApplyReview";
import { ActivityPerpose, StatusMap } from "./Data";

const ActivityApplyList = LibAppView.withService({
    reqEndPoints: [{
        endPoint: "setting.configList",
        name: "category",
        uri: { config: "lawDocType" }
    }]
})((props) => {
    const microApp = LibAppView.useMicroApp();
    const reviewActivityApply = useActivityApplyReview();
    const listRef = useRef<any>();

    const [ currentUserId ]= useState(() => {
        const userData = JSON.parse(sessionStorage.getItem("AdminData") || "{}");
        return userData.userId;
    });
     
    const deleteAction = useDelete({
        endPoint: "activity.applyDelete",
        cancelEndPoint: "activity.applyWithdraw",
        data: {},
        listRef
    });
    const columns = useMemo(() => ([{
        title: "单位名称",
        dataIndex: "hostOrganization",
        width: 100,
        render: (info: string, data: any) => {
            return (<Button type="link" style={{whiteSpace: "normal",textAlign: "left"}} onClick={() => reviewActivityApply.show(data.id)}>{info}</Button>);
        }
    }, {
        title: "活动目的",
        dataIndex: "activityPurpose",
        width: 160,
        render: (info: string) => {
            const infoList = info?.length > 0 ? JSON.parse(info) : [];
            return (<>
                {
                    infoList.map((item: any) => {
                        return <Tag key={item} color={"geekblue"}>{item}</Tag>;
                    })
                }
            </>);
        }
    },
    {
        title: "联系人",
        dataIndex: "contactor",
        width: 100,
    },{
        title: "联系电话",
        dataIndex: "mobile",
        width: 120
    },{
        title: "服务时段",
        dataIndex: "activityPeriod",
        width: 100
    },{
        title: <FormattedMessage id="admin.pages.menus.edit.status"/>,
        dataIndex: "status",
        width: 100,
        render: (status: number) => {
            return (<ResourceStatus status={status} dataMap={StatusMap} />);
        }
    },{
        title: "受理用户",
        dataIndex: "taskUserName",
        width: 120,
        render: (name: string) => {
            return name ?? "待审批";
        }
    },{
        title: "创建用户",
        dataIndex: "createUserName",
        width: 120
    },{
        title: <FormattedMessage id="admin.pages.operate.edit" />,
        dataIndex: "name",
        width: 140,
        render: (name: string, data: any) => {
            const nextProps = (!data.owner || data.status != 0) ? { disabled: true } : {};
            const cancelProps = data.status != 1 || !data.owner ? { disabled: true } : {};
            // 只有状态是0-编辑状态，创建用户可编辑， 1-带审核所有人不可编辑
            // 2-待入库，受理用户可编辑，其他人不可编辑,申请人也可编辑，受理用户可做入库操作
            // 3-已入库，所有人不可编辑
            const editProps = data.status === 2 ? (data.taskUser === currentUserId || data.createUser === currentUserId ? {} : { disabled: true }) : ( data.status === 0 ? nextProps : { disabled: true} );
            return (<>
                <AdminRight authRight="editable" mode="disabled" nextProps={editProps}>
                    <Button size="small" onClick={()=>{
                        if(data.status === 2) {
                            microApp.startJourney("editApplyDetails", {
                                state: {
                                    ...data,
                                    content: data.requirement || "",
                                    region: data.region && data.region.length > 0 ? JSON.parse(data.region) : []
                                }
                            });
                        } else {
                            microApp.startJourney("editDetails", {
                                state: data
                            });
                        }
                    }}>
                        <FormattedMessage id="admin.pages.operate.edit"/>
                    </Button>
                </AdminRight>
                {
                    [0,1].includes(data.status) && <><AdminRight authRight="editable" mode="disabled" nextProps={cancelProps}>
                        <Button size="small" onClick={()=>{
                            deleteAction.cancel({
                                ...data,
                                status: 0
                            })
                        }}>
                            <FormattedMessage id="admin.pages.operate.cancel"/>
                        </Button>
                    </AdminRight>
                    <AdminRight authRight="deleteable" mode="disabled" nextProps={nextProps}>
                        <Button size="small" onClick={() => {
                            deleteAction.delete({
                                ...data,
                                status: -1
                            });
                        }}><FormattedMessage id="admin.pages.operate.delete"/></Button>
                    </AdminRight>
                    </>
            }
            </>);
        }
    }]), [currentUserId]);
    const searchFields = useMemo<Admin.IAdvancedField[]>(() => ([{
        label: "申报单位",
        name: "hostOrganization",
        type: "Input"
    }, {
        label: "活动目的",
        name: "activityPurpose",
        type: "Select",
        data: ActivityPerpose || []
    }, {
        label: "活动联系人",
        name: "contactor",
        type: "Input"
    }]), []);
    useLayoutEffect(() => {
        microApp.registeJourney({
            name: "editDetails",
            title: "Edit category",
            stepJourney: true,
            isTempJourney: true,
            steps: [{
                isMemoryPage: true,
                page: "admin.activityApplyEdit"
            }]
        });
        microApp.registeJourney({
            name: "editApplyDetails",
            title: "Edit Apply details",
            stepJourney: true,
            isTempJourney: true,
            steps: [{
                isMemoryPage: true,
                page: "admin.activityApplyDetailEdit"
            }]
        });
        //activityApplyDetailEdit
    },[]);
    return (<>
        <ResourceList
            refApi={listRef}
            tableColumns={columns}
            searchFields={searchFields}
            tableWidth={1200}
            listEndPoint={{
                endPoint: "activity.applyList",
                formatResponse: (resp: any) => {
                    const listData: any[] = resp.data || [];
                    return listData.map((item: any) => {
                        // const publishOwner = publishOwnerList.find((item2: any) => item2.value === item.publishOwner);
                        return {
                            ...item,
                            // publishOwnerName: publishOwner?.label || "未知",
                        };
                    });
                }
            }}
            Operators={() => {
                return (<AdminRight authRight="editable" mode="disabled">
                    <Button type="primary" onClick={() => {
                        microApp.startJourney("editDetails");
                    }}>
                        <PlusOutlined />
                        <span><FormattedMessage id="admin.pages.operate.add" /></span>
                    </Button>
                </AdminRight>);
            }}
        />
        {reviewActivityApply.Provider}
        </>
    );
});

export default ActivityApplyList;
